# https://open.dingtalk.com/document/orgapp/robot-sends-nail-message
import requests
import time
import hmac
import base64
import hashlib
import urllib

from retry import retry


@retry(tries=3, delay=5)
def ding_sent(msg,secret = 'SEC98a989c187fa34eb470c74a2e86a6c8298466703cfb4ace2a5be60426e339ed8',token='9f6665157098eba59e3f195f02dae72beeb561218ee5b879962b3372ada4b164'):
    timestamp = str(round(time.time() * 1000))
    # secret = 'SEC98a989c187fa34eb470c74a2e86a6c8298466703cfb4ace2a5be60426e339ed8'
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    # print(timestamp)
    # print(sign)
    #"https://oapi.dingtalk.com/robot/send?access_token=fa9f58b518eeafd9045c6d003f8105d701b9b73d6e0991471181802381d27d1d"
    url = 'https://oapi.dingtalk.com/robot/send?access_token='+token+'&timestamp=%s&sign=%s' % (
    timestamp, sign)

    data = {
        "msgtype": "text",
        "text": {
            "content": msg
        }
    }

    res = requests.post(url, json=data)
    print(res.text)

# dwqb
# SEC4fd4ada9e331ba16cf7fc4d21934f608031c839faae44ca47294da864a727bfd
# https://oapi.dingtalk.com/robot/send?access_token=5d0c18430c693fcd552f054572b806bf66351be350d3807af134f51a438e9f2e

#ding_sent('test','SEC4fd4ada9e331ba16cf7fc4d21934f608031c839faae44ca47294da864a727bfd','5d0c18430c693fcd552f054572b806bf66351be350d3807af134f51a438e9f2e')